import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
export const menu_routes: RouteRecordRaw[] = [
  {
    path: "/home",
    component: () => import("@/views/home/indexHome.vue"),
    name: "Home",
    meta: {
      title: "首页",
    },
  },
  {
    path: "/list",
    component: () => import("@/views/list/indexLogin.vue"),
    name: "List",
    meta: {
      title: "列表",
    },
  },
  {
    path: "/set",
    component: () => import("@/views/set/indexLogin.vue"),
    name: "Set",
    meta: {
      title: "设置",
      roles: ["admin"],
    },
  },
  {
    path: "/upload",
    component: () => import("@/views/upload/indexLogin.vue"),
    name: "Upload",
    meta: {
      title: "上传",
      roles: ["admin"],
    },
  },
  {
    path: "/403",
    component: () => import("@/views/403/indexView.vue"),
    name: '403',
    meta: {
      title: "403",
      hidden: true
    },
  },
];

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("@/layout/indexMainLayout.vue"),
    name: "Layout",
    redirect: "/home",
    children: menu_routes,
  },
  {
    path: "/login",
    component: () => import("@/views/login/indexLogin.vue"),
    name: "Login",
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from) => {
  const userInfo = (store.state as any).user.userInfo;
  const roles = to.meta.roles as string[];
  if (!roles) {
    return true;
  }

  if (userInfo.role === "admin") {
    return true;
  }

  if (roles.includes(userInfo.role)) {
    return true;
  } else {
    // 拦截 求 403页面 没有权限

    return { name: '403' };
  }
});

export default router;
